﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Net;
using System.Windows;

namespace modaid
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lp1, string lp2);

        [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("USER32.DLL")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_SHOWNORMAL = 1; 

        public const int ITEMCOUNT = 206;
        public const int BLOCKCOUNT = 78;
        public const int FUNCTIONCOUNT = 8;

        item[] itemList = new item[ITEMCOUNT];
        item[] blockList = new item[BLOCKCOUNT];
        item[] direction = new item[6];
        item[] selectFunction = new item[FUNCTIONCOUNT];

        public Form1()
        {
            InitializeComponent();
            FillComboBox();
            labelEnterCmd.Text = "Here you can enter a custom command" + Environment.NewLine + " for Minecraft to execute!" + Environment.NewLine + Environment.NewLine + "eg: /tp Desater";
        }

        private void FillComboBox()
        {
            //First the item-combobox
            String currentDir = Directory.GetCurrentDirectory();
            StreamReader reader = new StreamReader(currentDir + "\\items.txt");
            try
            {
                String currentLine;
                string[] parts;
                int i = 0;
                do
                {
                    currentLine = reader.ReadLine();
                    parts = currentLine.Split('.');
                    itemList[i] = new item();
                    itemList[i].setName(parts[0]);
                    itemList[i].setCode(parts[1]);
                    comboBoxItems.Items.Add(itemList[i].toString());
                    i++;
                    if (i == ITEMCOUNT)
                    {
                        for (int k = 0; k < 6; k++)
                        {
                            currentLine = reader.ReadLine();
                            parts = currentLine.Split('.');
                            direction[k] = new item();
                            direction[k].setName(parts[0]);
                            direction[k].setCode(parts[1]);
                            comboBoxDirection.Items.Add(direction[k].toString());
                        }
                        for (int k = 0; k < FUNCTIONCOUNT; k++)
                        {
                            currentLine = reader.ReadLine();
                            parts = currentLine.Split('.');
                            selectFunction[k] = new item();
                            selectFunction[k].setName(parts[0]);
                            selectFunction[k].setCode(parts[1]);
                            comboBoxSelect.Items.Add(selectFunction[k].toString());
                        }
                        for (int k = 0; k < BLOCKCOUNT; k++)
                        {
                            currentLine = reader.ReadLine();
                            parts = currentLine.Split('.');
                            blockList[k] = new item();
                            blockList[k].setName(parts[0]);
                            blockList[k].setCode(parts[1]);
                            comboBoxBlock1.Items.Add(blockList[k].toString());
                            comboBoxBlock2.Items.Add(blockList[k].toString());
                        }
                    }
                }
                while (reader.Peek() != -1 && i < ITEMCOUNT);
                
            }
            catch
            {
                MessageBox.Show("Error in file.");
            }
            finally
            {
                reader.Close();
            }
        }

        private void sleepS(int mseconds)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; ; i++)
            {
                if (i % 100000 == 0)
                {
                    sw.Stop();
                    if (sw.ElapsedMilliseconds > mseconds)
                    {
                        break;
                    }
                    else
                    {
                        sw.Start();
                    }
                }
            }
            return;
        } 

        private void buttonGive_Click(object sender, EventArgs e)
        {
            String item = "", user = "", count = "";
            String errormessage = "";

            if (comboBoxItems.SelectedIndex >= 0)
                item = itemList[comboBoxItems.SelectedIndex].getCode();
            else
                errormessage += "\t* Select an item.\n";

            if(textBoxUser.Text != "")
                user = textBoxUser.Text;
            else
                errormessage += "\t* Enter in a user.\n";

            if (textBoxAmount.Text != "")
                count = textBoxAmount.Text;
            else
                errormessage += "\t* Enter an amount.\n";

            if(errormessage != "")
                MessageBox.Show("Please check the following values!\n\n" + errormessage);
            else
                SendToScreen( "/give " + user + " " + item + " " + count, true );
        }

        private void SendToScreen(String input, bool restoreMODAID)
        {
            IntPtr handle = FindWindow(null, "Minecraft");
            if (!handle.Equals(IntPtr.Zero))
            {
                // activate window
                try
                {
                    ShowWindow(handle, SW_SHOWNORMAL);
                    sleepS(100);
                    SendKeys.Flush();
                    SendKeys.Send("{ESC}");
                    sleepS(100);
                    SendKeys.Send("t");
                    sleepS(100);
                    SendKeys.Send(input);
                    sleepS(100);
                    SendKeys.Send("{ENTER}");
                }
                catch
                {
                    //SetForegroundWindow(handle);
                }
                if (SetForegroundWindow(handle))
                //if (ShowWindow(handle, SW_SHOWNORMAL))
                {
                    sleepS(100);
                    SendKeys.Flush();
                    SendKeys.Send("{ESC}");
                    sleepS(100);
                    SendKeys.Send("t");
                    sleepS(100);
                    SendKeys.Send(input);
                    sleepS(100);
                    SendKeys.Send("{ENTER}");
                }
                else
                    MessageBox.Show("Minecraft not on foreground!");
                if (restoreMODAID)
                {
                    handle = FindWindow(null, "MODaid");
                    SetForegroundWindow(handle);
                }
            }
            else
                MessageBox.Show("Minecraft not found!");
        }

        private void buttonResize_Click(object sender, EventArgs e)
        {
            String amount = "", opposite = "", directionString = "", function = "", original = "", replacement = "";
            String errormessage = "";

            if (comboBoxSelect.SelectedIndex < 0)
            {
                errormessage += "\t* Select a function.\n";
            }
            else if (comboBoxSelect.SelectedIndex == 2 || comboBoxSelect.SelectedIndex == 4 || comboBoxSelect.SelectedIndex == 5 || comboBoxSelect.SelectedIndex == 7) //replace + set
            {
                if(comboBoxBlock1.SelectedIndex >= 0)
                    original = blockList[comboBoxBlock1.SelectedIndex].getCode();

                if (comboBoxBlock2.SelectedIndex >= 0)
                    replacement = blockList[comboBoxBlock2.SelectedIndex].getCode();
                else
                    errormessage += "\t* Select an item to replace the original with.\n";

                function = selectFunction[comboBoxSelect.SelectedIndex].getCode();
            }
            else
            {
                if (textBoxSelectAmount.Text != "")
                    amount = textBoxSelectAmount.Text;
                else
                    errormessage += "\t* Enter in an amount.\n";

                if (comboBoxDirection.SelectedIndex >= 0)
                    directionString = direction[comboBoxDirection.SelectedIndex].getCode();
                else
                    errormessage += "\t* Select a direction.\n";

                if (textBoxOpposite.Text != "")
                    opposite = textBoxOpposite.Text;

                function = selectFunction[comboBoxSelect.SelectedIndex].getCode();
            }

            if (errormessage != "")
                MessageBox.Show("Please check the following values!\n\n" + errormessage);
            else
                if (comboBoxSelect.SelectedIndex == 4) //replace
                    if(original != "")
                        SendToScreen("//replace " + original + " " + replacement, true);
                    else
                        SendToScreen("//replace " + replacement, true);
                else if (comboBoxSelect.SelectedIndex == 2 || comboBoxSelect.SelectedIndex == 5 || comboBoxSelect.SelectedIndex == 7) //faces + set + walls
                    SendToScreen("//" + function + " " + replacement, true);
                else
                    if(opposite != "")
                        SendToScreen("//" + function + " " + amount + " " + opposite + " " + directionString, true);
                    else
                        SendToScreen("//" + function + " " + amount + " " + directionString, true);
        }

        private void comboBoxSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxSelect.SelectedIndex == 4) //replace
            {
                enableSelectors("replace");
                
            }
            else if (comboBoxSelect.SelectedIndex == 2 || comboBoxSelect.SelectedIndex == 5 || comboBoxSelect.SelectedIndex == 7) //faces + set + walls
            {
                enableSelectors("set");
            }
            else if (comboBoxSelect.SelectedIndex == 3 || comboBoxSelect.SelectedIndex == 6) //move + shift
            {
                enableDirections("move");      
            }
            else
            {
                enableDirections("other"); 
            }
        }

        private void buttonUndo_Click(object sender, EventArgs e)
        {
            SendToScreen("//undo", true);
        }

        private void buttonRedo_Click(object sender, EventArgs e)
        {
            SendToScreen("//redo", true);
        }

        private void buttonEnterCmd_Click(object sender, EventArgs e)
        {
            if(textBoxEnterCmd.Text != "")
                SendToScreen(textBoxEnterCmd.Text, true);
            else
                MessageBox.Show("No text entered.");
        }

        private void toolStripButtonAbout_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Made by Desater!\n\n\t* Push Alt+Z for convenient use of the Instant Messenger!");
        }

        private void buttonClearField_Click(object sender, EventArgs e)
        {
            if(textBoxEnterCmd.Text != "")
                textBoxEnterCmd.Text = "";
        }

        private void enableSelectors( String argument )
        {
            panelSelect.Visible = false;
            panelSelect.Enabled = false;
            panelReplace.Visible = true;
            panelReplace.Enabled = true;
            if (argument.Equals("replace"))
            {
                comboBoxBlock1.Visible = true;
                comboBoxBlock1.Enabled = true;
                labelOriginal.Visible = true;
                labelOriginal.Enabled = true;
            }
            else if (argument.Equals("set"))
            {
                comboBoxBlock1.Visible = false;
                comboBoxBlock1.Enabled = false;
                labelOriginal.Visible = false;
                labelOriginal.Enabled = false;
            }
        }

        private void enableDirections( String argument )
        {
            comboBoxBlock1.Visible = true;
            comboBoxBlock1.Enabled = true;
            labelOriginal.Visible = true;
            labelOriginal.Enabled = true;
            panelReplace.Visible = false;
            panelReplace.Enabled = false;
            panelSelect.Visible = true;
            panelSelect.Enabled = true;
            if (argument.Equals("move"))
            {
                labelOpposite.Visible = false;
                labelOpposite.Enabled = false;
                textBoxOpposite.Visible = false;
                textBoxOpposite.Enabled = false;
            }
            else if (argument.Equals("other"))
            {
                labelOpposite.Visible = true;
                labelOpposite.Enabled = true;
                textBoxOpposite.Visible = true;
                textBoxOpposite.Enabled = true;
            }
               
        }

        private void buttonReadMail_Click(object sender, EventArgs e)
        {
            SendToScreen("/mail read", true);
        }

        private void buttonClearMail_Click(object sender, EventArgs e)
        {
            SendToScreen("/mail clear", true);
        }

        private void buttonSendMail_Click(object sender, EventArgs e)
        {
            String user = "", message = "";
            String errormessage = "";

            if (textBoxToMail.Text != "")
                user = textBoxToMail.Text;
            else
                errormessage += "\t* Enter in a user.\n";

            if (textBoxMail.Text != "")
                message = textBoxMail.Text;
            else
                errormessage += "\t* Enter a message.\n";

            if (errormessage != "")
                MessageBox.Show("Please check the following values!\n\n" + errormessage);
            else
                SendToScreen("/mail send " + user + " " + message, true);
        }

        private void buttonSendMessage_Click(object sender, EventArgs e)
        {
            String user = "", message = "";
            String errormessage = "";

            if (textBoxToMessage.Text != "")
                user = textBoxToMessage.Text;
            else
                errormessage += "\t* Enter in a user.\n";

            if (textBoxMessage.Text != "")
                message = textBoxMessage.Text;
            else
                errormessage += "\t* Enter a message.\n";

            if (errormessage != "")
                MessageBox.Show("Please check the following values!\n\n" + errormessage);
            else
                SendToScreen("/msg " + user + " " + message, false);    
        }
    }
}
